package com.example.androidreviewapp

import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.example.androidreviewapp.databinding.ActivityMainBinding
import com.example.androidreviewapp.databinding.LayoutItemIconTextBinding
import com.example.androidreviewapp.model.RunAppInfo
import com.shenghuai.bclient.stores.adapter.ListSimpleAdapter
import com.shenghuai.bclient.stores.util.ActivityEt.getLayoutRootView
import com.shenghuai.bclient.stores.util.SafeUtils


class MainActivity : AppCompatActivity(R.layout.activity_main) {

    private val spanCount = 4
    private lateinit var runAppInfoAddHelper: RunAppInfosAddHelper

    /*WebViewActivity.launch(
           this,
           "https://mbd.baidu.com/newspage/data/landingsuper?context={\"nid\":\"news_9827603875880293712\"}&n_type=0&p_from=1"
       )*/

    private lateinit var activityMainBinding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        activityMainBinding = ActivityMainBinding.bind(getLayoutRootView())
        val appListRv = activityMainBinding.appListRv
        appListRv.layoutManager = GridLayoutManager(this, spanCount).apply {
        }
        val data = arrayListOf<RunAppInfo>()
        val adapter = ListSimpleAdapter(this, data, R.layout.layout_item_icon_text)
        appListRv.adapter = adapter
        @Suppress("UNCHECKED_CAST")
        adapter.itemDataCallback = callback@{ h, t, pos ->

            val itemView = h?.itemView ?: return@callback
            if (t == null) return@callback

            val bind = DataBindingUtil.bind<LayoutItemIconTextBinding>(itemView) ?: return@callback
            SafeUtils.safeRun {

                // 设置相应的intent的图片
                if (t.iconRes != 0) {
                    bind.icon.setImageResource(t.iconRes)
                } else {
                    if (t.activityComponentName != null) {
                        setActivityIcon(bind.icon, t.activityComponentName)
                    } else {
                        try {
                            val applicationIcon = packageManager.getApplicationIcon(t.packageName)
                            bind.icon.setImageDrawable(applicationIcon)
                        } catch (ex: Throwable) {
                            println("xxxx getApplicationIcon $ex")
                        }
                    }
                }

            }
            bind.title.text = t.name

            itemView.setOnClickListener {

                // 打开启动相应的intent
                if (t.componentName != null) {
                    val intent = Intent(Intent.ACTION_MAIN)
                        .setComponent(t.componentName)
                        .setPackage(t.packageName)
                    try {
                        startActivity(intent)
                        return@setOnClickListener
                    } catch (ex: Throwable) {
                        ex.printStackTrace()
                    }

                }

                if (t.openIntentTask != null) {
                    t.openIntentTask?.run()
                    return@setOnClickListener
                }

                val launcherIntent = packageManager.getLaunchIntentForPackage(t.packageName)
                if (launcherIntent != null && packageManager.resolveActivity(
                        launcherIntent, PackageManager.MATCH_ALL
                    ) != null
                ) {
                    startActivity(launcherIntent)
                }

            }
        }

        activityMainBinding.root.post {
            runAppInfoAddHelper = RunAppInfosAddHelper(this)
            runAppInfoAddHelper.build(adapter)
        }

        initEvent()

    }

    private fun initEvent() {
        activityMainBinding.refreshButton.setOnClickListener {
            if (::runAppInfoAddHelper.isInitialized) {
                val adapter = activityMainBinding.appListRv.adapter
                @Suppress("UNCHECKED_CAST")
                runAppInfoAddHelper.refresh(adapter as ListSimpleAdapter<RunAppInfo>)
            }
        }
    }

    /**
     * 获取activity的图标
     */
    private fun setActivityIcon(imageView: ImageView, componentName: ComponentName?) {
        if (componentName == null) return
        SafeUtils.safeRun {
            val activityIcon = packageManager.getActivityIcon(componentName)
            imageView.setImageDrawable(activityIcon)
        }
    }


}